import Toast from './Toast';

let messageInstance: any = null;

function getInstance(props: any, callback: (notification: any) => void) {
  if (messageInstance) {
    messageInstance.destroy();
    messageInstance = null;
  }

  Toast.newInstance(props, (notification: any) => {
    return callback && callback(notification);
  });
}

function notice(
  message: string,
  icon: any,
  duration: number = 3,
  onClose?: () => void,
  className?: string
) {
  function close() {
    if (messageInstance) {
      messageInstance.destroy();
      messageInstance = null;
    }
    if (onClose) {
      onClose();
    }
  }

  getInstance(
    {
      message,
      icon,
      duration,
      onClose: close,
      className
    },
    (notification: any) => {
      messageInstance = notification;
    }
  );
}

export default {
  SHORT: 3,
  LONG: 8,
  show(
    message: string,
    duration?: number,
    onClose?: () => void,
    className?: string
  ) {
    return notice(message, null, duration, onClose, className);
  },
  success(message: string, duration?: number, onClose?: () => void) {
    return notice(message, 'lego_duohao1', duration, onClose);
  },
  fail(message: string, duration?: number, onClose?: () => void) {
    return notice(message, 'shop-shuoming', duration, onClose);
  },
  loading(message: string, duration?: number, onClose?: () => void) {
    return notice(message, 'lego_jiazai', duration, onClose);
  }
};
